package com.mmlc.meimei.lichengkongjian.classify;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.androidnetframe.BaseParentActivity;
import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.requestbean.BaseResponseBean;
import com.androidnetframe.responsejavabean.RequestError;
import com.mmlc.meimei.lichengkongjian.Adapter.FastBuyAdapter;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.customview.SwipeRecyclerView;
import com.mmlc.network.filter.GoodsCollectRequestFilter;
import com.mmlc.network.filter.MeiQiListRequestFilter;
import com.mmlc.network.responsebean.MeiQiFastListResponseBean;
import com.mmlc.utils.AppUtils;
import com.mmlc.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/12/5.
 */
public class MQFastBuyFragment extends LazyFragment  {

    //    @InjectView(R.id.swiperefresh)
//    SwipeRefreshLayout sflSwipe;
//    @InjectView(R.id.recyclerview)
//    RecyclerView rcRecyclerview;
//    @InjectView(R.id.swipeRecyclerView)
    boolean isFirstInit = true;
    SwipeRecyclerView mSwipeRecyclerView;
    private boolean isRefresh = false;//是否刷新中


//    @Override
//    protected int initResourceID() {
//        return R.layout.fragment_mqfastbuy;
//    }

    // 标志位，标志已经初始化完成。
    private boolean isPrepared;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mqfastbuy, container, false);
        //XXX初始化view的各控件
        mSwipeRecyclerView = (SwipeRecyclerView)view.findViewById(R.id.swipeRecyclerView);
        initView();
        isFirstInit = true;
        isPrepared = true;
        lazyLoad();
        return view;
    }
    @Override
    protected void lazyLoad() {
        if(!isPrepared || !isVisible) {
            return;
        }
        //填充各控件的数据
//        mSwipeRecyclerView.onRefresh();
        if(isFirstInit) {
            mSwipeRecyclerView.setRefreshing(true);
            isFirstInit = false;
        }
    }
    public FastBuyAdapter adapter;
    public List<MeiQiFastListResponseBean.DataBean.GoodslistBean> data;
    public int page = 0;
    public int page_size = 10;
    public boolean isLoadMore;
    public String id;

    public void initView() {
        id = getArguments().getString("id");
        //set color
        mSwipeRecyclerView.getSwipeRefreshLayout()
                .setColorSchemeColors(Color.RED);

        //set layoutManager
        mSwipeRecyclerView.getRecyclerView().setLayoutManager(new LinearLayoutManager(getActivity()));
        data = new ArrayList<>();
        adapter = new FastBuyAdapter(getActivity(),data);
        mSwipeRecyclerView.setAdapter(adapter);
        mSwipeRecyclerView.setOnLoadListener(new SwipeRecyclerView.OnLoadListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                isLoadMore = false;
                page = 0;
                initData(page);
            }

            @Override
            public void onLoadMore() {
                page++;
                isLoadMore = true;
                isRefresh = false;
                initData(page);
            }
        });

        //设置自动下拉刷新，切记要在recyclerView.setOnLoadListener()之后调用
        //因为在没有设置监听接口的情况下，setRefreshing(true),调用不到OnLoadListener

        adapter.setClickListener(new FastBuyAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                switch (view.getId()){
                    case R.id.tv_do:
                        Intent intent =new Intent(getActivity(),FastGoodsDetailActivity.class);
                        intent.putExtra("id",data.get(position).getId());
                        startActivity(intent);
                        break;
                    case R.id.iv_goodspic:
                        Intent it =new Intent(getActivity(),FastGoodsDetailActivity.class);
                        it.putExtra("id",data.get(position).getId());
                        startActivity(it);
                        break;
                    case R.id.ll_collect:
                        ImageView ivLike = (ImageView) view.findViewById(R.id.iv_like);
                        TextView tvCount = (TextView) view.findViewById(R.id.tv_lovecount);
                        goodsCollect(ivLike,tvCount,position);
                        break;
                }
            }
        });



    }


    //收藏
    private void goodsCollect(final ImageView ivLike, final TextView tvCount, final int position){
        GoodsCollectRequestFilter filter = new GoodsCollectRequestFilter((BaseParentActivity) getActivity());
        filter.requestBean.method = data.get(position).getIs_collected().equals("0") ? "goodsCollect" : "goodsUnCollect";
        filter.requestBean.goods_id = data.get(position).getId();
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<BaseResponseBean>() {
            @Override
            public void onSuccess(BaseResponseBean result) {

                if (data.get(position).getIs_collected().equals("0")) {
                    ivLike.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.liked));
                    tvCount.setText(""+(Integer.parseInt(data.get(position).getCollect_num())+1));
                    data.get(position).setIs_collected("1");
                    data.get(position).setCollect_num(""+(Integer.parseInt(data.get(position).getCollect_num())+1));
                    adapter.notifyDataSetChanged();
                    return;

                }else if(data.get(position).getIs_collected().equals("1")){
                    ivLike.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.like));
                    tvCount.setText(""+(Integer.parseInt(data.get(position).getCollect_num())-1)+"");
                    data.get(position).setIs_collected("0");
                    data.get(position).setCollect_num(""+(Integer.parseInt(data.get(position).getCollect_num())-1));
                    return;
                }
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess.toString());
            }
        });
    }

    private void initData(final int page) {
        MeiQiListRequestFilter filter = new MeiQiListRequestFilter((BaseParentActivity) getActivity());
        filter.requestBean.zg_flag = 1;
        filter.requestBean.cate_id = id;
        filter.requestBean.pageNow = page;
        filter.requestBean.pageSize = page_size;
        filter.requestBean.version = AppUtils.getVersionCode(getActivity())+"";
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<MeiQiFastListResponseBean>() {
            @Override
            public void onSuccess(MeiQiFastListResponseBean result) {

                if(result!=null){
                    if(isFirst){
                        data.addAll(result.getData().getGoodslist());
                        adapter.notifyDataSetChanged();
                        isFirst = false;
                        if(result.getData().getGoodslist().size()<page_size){
                            mSwipeRecyclerView.setLoadMoreEnable(false);
                        }
                        mSwipeRecyclerView.complete();
                        return;
                    }
                    if(isLoadMore ) {
                        data.addAll(result.getData().getGoodslist());
                        isLoadMore = false;
                        if(result.getData().getGoodslist().size()==0){
                            mSwipeRecyclerView.onNoMore("一  End  一");
                        }else{
                            mSwipeRecyclerView.stopLoadingMore();
                            adapter.notifyDataSetChanged();
                        }
                        adapter.notifyDataSetChanged();
                        return;
                    }else if(isRefresh){
                        if(result.getData().getGoodslist().size()<page_size){
                            mSwipeRecyclerView.setLoadMoreEnable(false);
                        }
                        if(result.getData().getGoodslist().size() == 0){
                            mSwipeRecyclerView.complete();
                            isRefresh = false;
                            return;
                        }

                        data.clear();
                        data.addAll(result.getData().getGoodslist());
                        isRefresh = false;
                        mSwipeRecyclerView.complete();
                        adapter.notifyDataSetChanged();
                        return;
                    }
                }else{
                    ToastUtils.showToast("数据类型错误");
                }

            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
                mSwipeRecyclerView.complete();
                mSwipeRecyclerView.stopLoadingMore();
            }
        });
    }

    public boolean isFirst=true;

}
